package com.own.component.sms.core.core;

import com.own.component.sms.core.base.BaseSmsSendService;
import com.own.component.sms.core.em.SmsSendMethodEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * SmsSendSpringHook
 *
 * @author chenxueli
 * @date 2023-06-21 15:52:23
 */
@Slf4j
@Component
@SuppressWarnings("all")
public class SmsSendSpringHook implements ApplicationContextAware, ApplicationListener<ApplicationEvent> {

    private static final Map<SmsSendMethodEnum, BaseSmsSendService> SMS_SEND_MAP = new LinkedHashMap<>(8);
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        SmsSendSpringHook.applicationContext = context;
    }

    /**
     * 处理所有的获取用户信息的内容
     *
     * @param loginUser 登录的用户信息
     */
    public BaseSmsSendService get(SmsSendMethodEnum name) {
        return SMS_SEND_MAP.get(name);
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationReadyEvent) {
            applicationContext.getBeansOfType(BaseSmsSendService.class).forEach((key, service) -> {
                var type = service.type();
                if (SMS_SEND_MAP.containsKey(type)) {
                    log.error("短信发送工具===>【{}:{}】注册失败，已经存在相同的名称", type, service);
                }
                SMS_SEND_MAP.put(type, service);
                log.debug("短信发送工具===>【{}:{}】完成注册", type, service);
            });
        }
    }

}
